Tack.Player = new Class({
	initialize: function (game) {
		this.previousScene = '';
		this.state = new Hash();
		this.subscribers = [];

		this.ignoreWords = ['to', 'the'];

		this.synonyms = {
			take: ['acquire', 'collect', 'fetch', 'grab', 'get', 'pick up'],
			inspect: ['analyze', 'check', 'examine', 'investigate', 'look at', 'scrutinize', 'view'],
			go: ['advance', 'march', 'move', 'run', 'stride', 'stroll', 'travel', 'walk', 'wander']
		};

		if (game) this.setGame(game);
	},

	endGame: function () {
		if (!this.playing) return;

		this.playing = false;
		this.write('The game has ended.', 'message');
	},

	goToScene: function (scene) {
		if (this.scene) this.previousScene = this.scene.name;
		(this.scene = scene).triggerEvent(this, 'entering');
	},

	play: function (command) {
		var original = command;

		if ($type(command) == 'string') {
			if (!this.playing) {
				this.write('The game has ended.', 'message');
			}

			command = command
				.toLowerCase()
				.replace(new RegExp('\\b(' + this.ignoreWords.join('|') + ')\\b', 'g'), '')
				.replace(/ {2,}/g, ' ');

			$each(this.synonyms, function (list, to) {
				for (var i = 0; i < list.length; i++) {
					var c = command.replace(new RegExp('^' + list[i] + '\\b'), to);
					if (c != command) {
						command = c;
						return;
					}
				}
			});

			if (command != original)
				this.write('Command interpreted as \'' + command + '\'.', 'debug');

			this.scene.triggerEvent(this, 'command', command);
		} else if (!this.playing) {
			this.state.empty();
			this.playing = true;
			this.write('You are now playing ' + this.game.title + ' by ' + this.game.author + '.', 'message');
			this.goToScene(this.game.startingScene);
		}
	},

	setGame: function (game) {
		this.endGame();
		this.game = game;
	},

	subscribe: function (console) {
		this.subscribers.push(console);
	},

	unsubscribe: function (console) {
		this.subscribers.remove(console);
	},

	write: function (text, type) {
		this.subscribers.each(function (s) { s.write(text, type); });
	}
});
